import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import type { IRootState } from './index'
import { Actions, Mutations } from '@/enum/dict'
import { dictFindKeys } from '@/api/dict'
import {
  parkTypeOptions,
  parkLevelOptions,
  economicTypeOptions,
  landTypeOptions,
  sellTypeOptions,
  landAreaRange,
  landPriceRange,
  rentOrSaleOptions,
  buildingAreaRange,
  buildingPriceRange,
  buildingRentRange,
  projectTypeOptions,
  projectStatusOptions,
} from '@/components/admin/manage/carrier/common/dictionary'

export interface ITreeState {
  codes: Record<string, any[]>
}

export const state: () => ITreeState = () => ({
  codes: {
    park_type: parkTypeOptions,
    park_level: parkLevelOptions,
    park_economic_type: economicTypeOptions,
    land_type: landTypeOptions,
    sell_type: sellTypeOptions,
    land_area_range: landAreaRange,
    land_price_range: landPriceRange,
    rent_or_sale: rentOrSaleOptions,
    building_area_range: buildingAreaRange,
    building_price_range: buildingPriceRange,
    building_rent_range: buildingRentRange,
    project_type: projectTypeOptions,
    project_status: projectStatusOptions,
  },
})

export const mutations: MutationTree<ITreeState> = {
  [Mutations.SET_CODES](state, payload) {
    state.codes = payload
  },
}

export const actions: ActionTree<ITreeState, IRootState> = {
  async [Actions.getCodes]({ commit, state }, keys: string[]) {
    let result = {}
    const newKeys: any = []
    keys.forEach((k) => {
      if (state.codes[k]) {
        result[k] = state.codes[k]
      } else {
        newKeys.push(k)
      }
    })

    // 需要根据接口返回的数据结构修改
    if (newKeys.length > 0) {
      const newCodes = await dictFindKeys(newKeys)
      console.log('newCodes', newCodes)
      result = {
        ...result,
        ...newCodes,
      }

      commit(Mutations.SET_CODES, {
        ...state.codes,
        ...newCodes,
      })
    }

    return result
  },
}

export const getters: GetterTree<ITreeState, IRootState> = {
  codes: (state) => state.codes,
}
